package com.atguigu.edu.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.edu.realtime.app.func.BeanToJsonStrFunction;
import com.atguigu.edu.realtime.bean.UserLoginBean;
import com.atguigu.edu.realtime.util.DateFormatUtil;
import com.atguigu.edu.realtime.util.DorisUtil;
import com.atguigu.edu.realtime.util.MyKafkaUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.restartstrategy.RestartStrategies;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.streaming.api.datastream.AllWindowedStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

public class DwsUserUserLoginWindow {
    public static void main(String[] args) {
        //TODO 1.基本环境准备
        //1.1 指定流处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //1.2 设置并行度
        env.setParallelism(4);
        //TODO 2.检查点相关的设置
        env.enableCheckpointing(5000L);
        env.setRestartStrategy(RestartStrategies.fixedDelayRestart(1, org.apache.flink.api.common.time.Time.seconds(1L)));
        //TODO 3.从kafka的主题中读取数据
        String topic = "dwd_user_login";
        String groupId = "dws_user_user_login_group";
        KafkaSource<String> kafkaSource = MyKafkaUtil.getKafkaSource(topic, groupId);
        //3.3 消费数据  封装为流
        DataStreamSource<String> kafkaStrDS
                = env.fromSource(kafkaSource, WatermarkStrategy.noWatermarks(), "kafka_source");
        //TODO 4.对流中数据类型进行转换    jsonStr->jsonObj
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaStrDS.map(JSON::parseObject);
        //TODO 6.指定Watermark以及提取事件时间字段
        SingleOutputStreamOperator<JSONObject> wmDs = jsonObjDS.assignTimestampsAndWatermarks(
                WatermarkStrategy
                        .<JSONObject>forMonotonousTimestamps()
                        .withTimestampAssigner(
                                new SerializableTimestampAssigner<JSONObject>() {
                                    @Override
                                    public long extractTimestamp(JSONObject jsonObj, long recordTimestamp) {
                                        return jsonObj.getLong("ts");
                                    }
                                }
                        )
        );
        //TODO 7.按照用户id进行分组
        KeyedStream<JSONObject, String> keyedStrDs = wmDs.keyBy(jsonObj -> jsonObj.getString("userId"));
        //wmDs.print("wm");
        //TODO 8.使用Flink的状态编程  判断是否为独立用户以及回流用户 jsonObj->实体类
        SingleOutputStreamOperator<UserLoginBean> processDs = keyedStrDs.process(new KeyedProcessFunction<String, JSONObject, UserLoginBean>() {
            private ValueState<String> lastLoginDateState;

            @Override
            public void open(Configuration parameters) throws Exception {
                ValueStateDescriptor<String> valueStateDescriptor
                        = new ValueStateDescriptor<String>("valueStateDescriptor", String.class);

                lastLoginDateState = getRuntimeContext().getState(valueStateDescriptor);
            }

            @Override
            public void processElement(JSONObject value, KeyedProcessFunction<String, JSONObject, UserLoginBean>.Context ctx, Collector<UserLoginBean> out) throws Exception {
                //获取当前用户上次登录日期
                String lastDate = lastLoginDateState.value();
                //获取当前登录日期
                Long ts = value.getLong("ts");
                String curDate = DateFormatUtil.toDate(ts);
                Long uuCt = 0L;
                Long backCt = 0L;
                if (StringUtils.isNotEmpty(lastDate)) {
                    //如果末次登陆日期不等于当天日期则独立用户数 uuCt 记为 1，并将状态中的末次登陆日期更新为当日，进一步判断。
                    if (!lastDate.equals(curDate)) {
                        uuCt = 1L;
                        lastLoginDateState.update(curDate);
                        Long days = ts - DateFormatUtil.toTs(lastDate) / 1000 / 60 / 60 / 24;
                        if (days >= 8) {
                            backCt = 1L;
                        }
                    }
                } else {
                    uuCt = 1l;
                    lastLoginDateState.update(curDate);
                }
                if (uuCt != 0L || backCt != 0L) {
                    out.collect(new UserLoginBean("", "", "", backCt, uuCt));
                }
            }
        });
        //processDs.print("process");
        //TODO 9.开窗
        AllWindowedStream<UserLoginBean, TimeWindow> windowDs = processDs.windowAll(TumblingEventTimeWindows.of(Time.seconds(10)));
        //TODO 10.聚合操作
        SingleOutputStreamOperator<UserLoginBean> reduceDs = windowDs.reduce(new ReduceFunction<UserLoginBean>() {
            @Override
            public UserLoginBean reduce(UserLoginBean value1, UserLoginBean value2) throws Exception {
                value1.setUuCt(value1.getUuCt() + value2.getUuCt());
                value1.setBackCt(value1.getBackCt() + value2.getBackCt());
                return value1;
            }
        }, new AllWindowFunction<UserLoginBean, UserLoginBean, TimeWindow>() {

            @Override
            public void apply(TimeWindow window, Iterable<UserLoginBean> values, Collector<UserLoginBean> out) throws Exception {
                String stt = DateFormatUtil.toYmdHms(window.getStart());
                String edt = DateFormatUtil.toYmdHms(window.getEnd());
                String cueDate = DateFormatUtil.toDate(window.getStart());
                for (UserLoginBean value : values) {
                    value.setStt(stt);
                    value.setEdt(edt);
                    value.setCurDate(cueDate);
                    out.collect(value);
                }
            }
        });
        reduceDs.print("reduce");
        //TODO 11.将聚合的结果写到Doris中
        reduceDs.map(new BeanToJsonStrFunction<>())
                .sinkTo(DorisUtil.getDorisSink("dws_user_user_login_window"));
        try {
            env.execute();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
